# -*- coding: utf-8 -*-

import datetime
import json
import pdb

from blueking.component.shortcuts import get_client_by_request, get_client_by_user
from common.mymako import render_json, render_mako_context
from get_capacity.celery_tasks import (async_task, celery_chain_task,
                                       custom_func1, save_task_log)
from host_status.models import HostStatusData, OperateHistoryData


def home(request):
    """
    Home Page
    """
    return render_mako_context(request, '/host_status/home.html')


def host_status(request):
    """
    Host Status
    """
    return render_mako_context(request, '/host_status/host_status.html')


def operate_history(request):
    """
    Operate History
    """
    return render_mako_context(request, '/host_status/operate_history.html')


def get_biz_list(request):
    """
    获取业务
    """
    biz_list = []
    client = get_client_by_request(request)
    kwargs = {
        'fields': ['bk_biz_id', 'bk_biz_name']
    }
    resp = client.cc.search_business(**kwargs)
    if resp.get('result'):
        data = resp.get('data', {}).get('info', {})
        for _d in data:
            biz_list.append({
                'name': _d.get('bk_biz_name'),
                'id': _d.get('bk_biz_id'),
            })
    result = {'result': resp.get('result'), 'data': biz_list}
    return render_json(result)


def get_ip_by_bizid(request):
    """
    获取业务主机IP
    """
    biz_id = int(request.GET.get('biz_id'))
    client = get_client_by_request(request)
    kwargs = {'bk_biz_id': biz_id,
              'condition': [{
                  'bk_obj_id': 'biz',
                  'fields': ['bk_biz_id'],
                  'condition': [
                      {
                            'field': 'bk_biz_id',
                            'operator': '$eq',
                            'value': biz_id
                            }
                  ]
              }]
              }
    resp = client.cc.search_host(**kwargs)

    ip_list = []
    if resp.get('result'):
        data = resp.get('data', {}).get('info', {})
        for _d in data:
            _hostinfo = _d.get('host', {})
            if _hostinfo.get('bk_host_innerip') not in ip_list:
                ip_list.append(_hostinfo.get('bk_host_innerip'))
    ip_all = [{'ip': _ip} for _ip in ip_list]
    result = {'result': resp.get('result'), 'data': ip_all}
    return render_json(result)


def get_joblist_by_bizid(request):
    """
    获取业务下的作业列表
    """
    biz_id = request.GET.get('biz_id')
    client = get_client_by_request(request)
    kwargs = {'bk_biz_id': biz_id}
    resp = client.job.get_job_list(**kwargs)
    job_list = []
    # pdb.set_trace()
    if resp.get('result'):
        data = resp.get('data', [])
        for _d in data:
            # 获取作业信息
            job_list.append({
                'job_id': _d.get('bk_job_id'),
                'job_name': _d.get('name'),
            })
    result = {'result': resp.get('result'), 'data': job_list}
    return render_json(result)

# ------------------------------------
# 执行作业，获取业务主机状态数据
# ------------------------------------


def ks_job(request):
    """
    执行查询主机状态脚本
    """
    biz_id = request.GET.get('biz_id')
    ip = request.GET.get('ip')

    ks_kwargs = {
        "bk_biz_id": biz_id,
        "script_id": 7,
        "script_timeout": 1000,
        "account": "root",
        "is_param_sensitive": 0,
        "script_type": 1,
        "ip_list": [
            {
                "bk_cloud_id": 0,
                "ip": ip
            }
        ],
    }
    # 调用作业平台API，或者作业执行实例ID
    client = get_client_by_request(request)
    resp = client.job.fast_execute_script(**ks_kwargs)
    #job_iid = resp.get('data').get('job_instance_id')
    # 写入数据库
    ldata = [ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
             client.bk_login.get_user().get('data').get('bk_username')]
    # OperateHistoryData.objects.save_data(ldata)
    OperateHistoryData.objects.create(ip=ip, operatetime=datetime.datetime.now(
    ), user=client.bk_login.get_user().get('data').get('bk_username'))
    return render_json(resp)


def get_mdc(request):
    """
    获取作业执行结果，并解析执行结果展示
    """
    # 调用作业平台API，或者作业执行详情
    job_instance_id = request.GET.get('job_instance_id')
    biz_id = request.GET.get('biz_id')
    ip = request.GET.get('ip')
    client = get_client_by_request(request)

    jobiid_kwargs = {

        "bk_biz_id": biz_id,
        "job_instance_id": job_instance_id
    }

    #resp = client.job.execute_job(**kwargs)
    #resp = client.job.fast_execute_script(**ks_kwargs)
    resp = client.job.get_job_instance_log(**jobiid_kwargs)
    #resp = client.job.get_job_detail(**kwargs)
    #isf = (resp.get('data')[0].get('is_finished'))
    if resp.get('data')[0].get('is_finished'):
        # 处理脚本运行结果
        hs = resp.get('data')[0].get('step_results')[0].get('ip_logs')[0]
        myhsarr = hs.get('log_content').strip().split('|')
        myhs = [{
            's_ip': hs.get('ip'),
            'run_time': myhsarr[0],
            's_mem': myhsarr[1],
            's_disk': myhsarr[2],
            's_cpu': myhsarr[3]
        }]
        result = {'is_finished': True, 'data': myhs}
        # 数据入库
        ldata = myhsarr.append(ip)
        # HostStatusData.objects.save_data(ldata)
        HostStatusData.objects.create(ip=ip, runtime=datetime.datetime.now(
        ), smem=myhsarr[1], sdisk=myhsarr[2], scpu=myhsarr[3])
    else:
        # 返回空
        result = {'is_finished': False, 'data': []}
    return render_json(result)


def get_hs(request):
    """
    获取主机状态
    """
    ip = request.GET.get('ip')

    num = 6
    max = HostStatusData.objects.filter(ip=ip).count()
    if max < num:
        chartdatas = HostStatusData.objects.filter(ip=ip)
        num = max
    else:
        chartdatas = HostStatusData.objects.filter(ip=ip)[max-6:max]
    xAxis = []
    mem_data = []
    disk_data = []
    cpu_data = []
    for i in range(0, num):
        xAxis.append(str(chartdatas[i].runtime))
        mem_data.append(float(chartdatas[i].smem.strip('%')))
        disk_data.append(float(chartdatas[i].sdisk.strip('%')))
        cpu_data.append(float(chartdatas[i].scpu.strip('%')))

    result = {"code": 0, 'result': True, "messge": "success",
              'data': {"xAxis": xAxis,
                         "series": [
                             {"name": u"内存", "type": "line", "data": mem_data},
                             {"name": u"磁盘", "type": "line", "data": disk_data},
                             {"name": u"CPU", "type": "line", "data": cpu_data},
                         ]
                       }
              }
    # pdb.set_trace()
    return render_json(result)


def get_oh(request):
    """
    获取操作历史
    """
    ldata = OperateHistoryData.objects.all()
    count = ldata.count()
    #pdb.set_trace()
    items = []
    for i in range(0, count):
        items.append({
            'index': i+1,
            'user': ldata[i].user,
            'operatetime': ldata[i].operatetime.strftime("%Y-%m-%d %H:%M:%S"),
            'ip': ldata[i].ip
        })
    #pdb.set_trace()
    result = {
        "catalogues": {
            "index": "#",
            "user": "用户",
            "operatetime": "操作时间",
            "ip": "操作IP"
        },
        "items": items
    }
    return render_json(result)
